package com.boot.main.service.impl;

import com.boot.main.entity.CcomUser;
import com.boot.main.entity.ScomAddress;
import com.boot.main.mapper.CcomUserMapper;
import com.boot.main.mapper.ScomAddressMapper;
import com.boot.main.response.ResponseData;
import com.boot.main.response.ResponseDataUtil;
import com.boot.main.service.IAddressService;
import com.boot.main.utils.IsNotEmptyUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AddressService implements IAddressService {
    @Resource
    private ScomAddressMapper addressMapper;

    @Resource
    private CcomUserMapper userMapper;

    public Long getUserId(){
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals =  subject.getPrincipals();
        String username = (String) principals.getPrimaryPrincipal();
        CcomUser user = userMapper.getUserByUserName(username);
        Long id = user.getId();
        return id;
    }

    @Override
    public ResponseData getAddress(Integer page, Integer limit, String name){
        Long userId = getUserId();
        List<ScomAddress> items = addressMapper.getAddress((page-1)*limit, limit, name, userId);
        Integer count = addressMapper.getTotalCount();
        Map map = new HashMap();
        map.put("datas",items);
        map.put("count", count);
        return ResponseDataUtil.success("获取地址成功", map);
    }

    @Override
    public ResponseData getDefaultAddress(){
        ScomAddress address = addressMapper.getDefaultAddress();
        return ResponseDataUtil.success("获取地址成功", address);
    }

    @Override
    public ResponseData saveAddress(ScomAddress address){
        if(address.getIs_default().equals(1)){
            addressMapper.updateAddressDefault();
        }
        address.setUser_id(getUserId());
        Integer num = addressMapper.saveAddress(address);
        if(IsNotEmptyUtil.isEmpty(num)){
            return ResponseDataUtil.error("保存地址失败", null);
        }
        return ResponseDataUtil.success("保存地址成功", null);
    }

    @Override
    public ResponseData updateAddress(ScomAddress address){
        if(address.getIs_default().equals(1)){
            addressMapper.updateAddressDefault();
        }
        Integer num = addressMapper.updateAddress(address);
        if(IsNotEmptyUtil.isEmpty(num)){
            return ResponseDataUtil.error("修改地址失败", null);
        }
        return ResponseDataUtil.success("修改地址成功", null);
    }

    @Override
    public ResponseData deleteAddress(Long id){
        Integer num = addressMapper.deleteAddress(id);
        return ResponseDataUtil.success("删除地址成功", null);
    }
}
